package com.juc.future.demo;

import lombok.Getter;

import java.util.Arrays;
import java.util.List;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ThreadLocalRandom;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

/**
 *性能提升案例
 *  同一款产品，同时搜索出同款产品在各大电商的售价
 */
public class CompletableFutureNetMallDemo {

    static List<NetMall> list = Arrays.asList(
            new NetMall("jd"),
            new NetMall("pdd"),
            new NetMall("pdd1"),
            new NetMall("pdd2"),
            new NetMall("pdd3"),
            new NetMall("pdd4"),
            new NetMall("tm")
    );

    //同步
    public static List<String> getPriceByStep(List<NetMall> list, String productName){
        return list.stream().map(netMall -> String.format(productName + "in %s price is %.2f", netMall.getMallName(), netMall.calcPrice(productName)))
                .collect(Collectors.toList());
    }
    //异步
    public static List<String> getPriceBySync(List<NetMall> list, String productName){
        return list.stream().map(netMall -> CompletableFuture.supplyAsync(()->
                String.format(productName + "in %s price is %.2f", netMall.getMallName(), netMall.calcPrice(productName))))
                .collect(Collectors.toList())
                .stream()
                .map(CompletableFuture::join)
                .collect(Collectors.toList());
    }
    public static void main(String[] args) {

        long state = System.currentTimeMillis();
        List<String> mysql = getPriceByStep(list, "mysql");
        mysql.forEach(m -> System.out.println(m));
        long end = System.currentTimeMillis();
        System.out.println("时长" + (end - state));



        long state1 = System.currentTimeMillis();
        List<String> mysql1 = getPriceBySync(list, "mysql");
        mysql1.forEach(m -> System.out.println(m));
        long end1 = System.currentTimeMillis();
        System.out.println("时长" + (end1 - state1));
    }
}

class NetMall{

    @Getter
    private String mallName;

    public NetMall(String mallName){
        this.mallName = mallName;
    }

    public double calcPrice(String productName) {
        try {
            TimeUnit.SECONDS.sleep(1); //假设每调用一次花费1s
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        return ThreadLocalRandom.current().nextDouble() * 2 + productName.charAt(0); //随机出了一个价格
    }

}
